package src.jdbc1;

import java.sql.*;

//数据的查询，删除，更新，增加
public class jdbcStudy2 {
    public static void main(String[] args) throws SQLException, ClassNotFoundException {
        jdbcStudy2 jdbcStudy2 = new jdbcStudy2();
        // jdbcStudy2.insertAll();
        //jdbcStudy2.update();
        jdbcStudy2.deleta();
        jdbcStudy2.findAll();

    }

    //数据的查询
    public void findAll() throws ClassNotFoundException, SQLException {
        //1.注册驱动
        Class.forName("com.mysql.cj.jdbc.Driver");
        //连接数据库
        Connection root = DriverManager.getConnection("jdbc:mysql://localhost:3306/stu?useSSL=false&serverTimezone=UTC", "root", "");
        //定义查询语句
        String sql = "select * from tbl_lixue";
        //获取查询对象
        Statement statement = root.createStatement();
        //执行sql语句
        ResultSet resultSet = statement.executeQuery(sql);
        //解析数据
        while (resultSet.next()) {
            int id = resultSet.getInt("id");
            String username = resultSet.getString("username");
            String password = resultSet.getString("password");
            System.out.println(id + "|" + username + "|" + password);
        }
        //释放资源
        resultSet.close();
        root.close();
        ;
    }

    //数据的增加
    public void insertAll() throws SQLException, ClassNotFoundException {
        //注册驱动
        Class.forName("com.mysql.cj.jdbc.Driver");
        //使用api连接数据库
        Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/stu?useSSL=false&serverTimezone=UTC", "root", "");
        //定义增加语句
        String sql = "insert into tbl_lixue values('ooo','8888',null )";
        //获取查询对象
        Statement statement = connection.createStatement();
        int i = statement.executeUpdate(sql);
    }

    //数据的删除
    //注册驱动
    public void update() throws ClassNotFoundException, SQLException {
        Class.forName("com.mysql.cj.jdbc.Driver");
        //使用api连接数据库
        Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/stu?useSSL=false&serverTimezone=UTC", "root", "");
        //定义语句
        String sql = "delete  from tbl_lixue where id=7";
        //连接数据库
        int i = connection.createStatement().executeUpdate(sql);
        System.out.println(i);
    }

    //数据的更新
    public void deleta() throws SQLException, ClassNotFoundException {
        //注册驱动
        Class.forName("com.mysql.cj.jdbc.Driver");
        //使用api连接数据库
        Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/stu?useSSL=false&serverTimezone=UTC", "root", "");
        //定义增加语句
        String sql= "update tbl_lixue set username='lixuen' where id=6";
        int i = connection.createStatement().executeUpdate(sql);
        System.out.println(i);
    }
}
